package com.leetcode.weekly.contest.no234th;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 覃国强
 * @date 2021-03-28 11:08
 */
public class A03_替换字符串中的括号内容 {


  public static void main(String[] args) {
    Solution solution = new Solution();
    String s = "(a)(b)";
    List<List<String>> knowledge = new ArrayList<>();
    knowledge.add(Arrays.asList("a","b"));
    knowledge.add(Arrays.asList("b","a"));

    String evaluate = solution.evaluate(s, knowledge);
    System.out.println(evaluate);

  }

  static
  class Solution {
    public String evaluate(String s, List<List<String>> knowledge) {
      if (s == null || s.length() == 0) {
        return "";
      }

      Map<String, String> map = new HashMap<>();
      if (knowledge != null && knowledge.size() > 0) {
        for (List<String> list : knowledge) {
          map.put(list.get(0), list.get(1));
        }
      }

      StringBuilder sb = new StringBuilder();
      char[] chars = s.toCharArray();
      for (int i = 0; i < chars.length; ) {
        if (chars[i] != '(') {
          sb.append(chars[i]);
          ++i;
        } else {
          ++i;
          StringBuilder key = new StringBuilder();
          while (chars[i] != ')') {
            key.append(chars[i]);
            ++i;
          }
          ++i;
          String value = map.get(key.toString());
          if (value == null) {
            sb.append("?");
          } else {
            sb.append(value);
          }
        }
      }
      return sb.toString();
    }
  }

}
